package edu.ynu.se.xiecheng.achitectureclass.GreenHouse.GreenhouseController;

import edu.ynu.se.xiecheng.achitectureclass.GreenHouse.GreenhouseDao.TokenDAO;
import edu.ynu.se.xiecheng.achitectureclass.GreenHouse.GreenhouseEntity.Token;
import edu.ynu.se.xiecheng.achitectureclass.common.dao.LogicDAO;
import edu.ynu.se.xiecheng.achitectureclass.common.entity.LogicEntity;
import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController<T extends LogicService<TokenDAO, Token, Long>, T1 extends LogicDAO<Token, Long>, T2 extends LogicEntity, L extends Number> {

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            // 登录
            subject.login(token);

            // 返回登录成功的信息
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("token", subject.getSession().getId()); // 返回 Session ID 作为 Token
            return ResponseEntity.ok(response);
        } catch (AuthenticationException e) {
            // 返回登录失败的信息
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "登录失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
}